package com.itic.mall.mobile.pay;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.order.persistence.model.Order;
import com.itic.mall.system.order.service.OrderService;


@Controller
@RequestMapping(value="/mobile/gongzhonghao")
public class GongzhonghaoPay
     extends BaseMobileInterface {
	
	@Autowired
	private OrderService orderService;
	
	

	/**
	 * 异步通知验证签名
	 * @return
	 */
	@RequestMapping(value="success")
	@ResponseBody
	public Map<String,Object> success(HttpServletRequest request,HttpServletResponse response,String orderId){
		Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		if( StringHelper.isNotBlank(orderId) ){
    			 Order order = orderService.get(orderId);
  			     if( null != order && "0".equals(order.getStatus()) ){
  				    result = paySuccess(order,"公众号");
  				    errorCode = SUCCESS_ERROR_CODE;
  		    	    errorMsg = SUCCESS_ERROR_MSG;
  			     }
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallProductInterface", "success", e.toString(),"公众号支付回调",e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
		
		
	}
	
	
	// 返回用IP地址  
    public String getIpAddr(HttpServletRequest request) {  
        String ip = request.getHeader(" x-forwarded-for ");  
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {  
            ip = request.getHeader(" Proxy-Client-IP ");  
        }  
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {  
            ip = request.getHeader(" WL-Proxy-Client-IP ");  
        }  
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
    }  
  
    // 随机字符串生成  
    public static String getRandomString(int length) { // length表示生成字符串的长度  
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";  
        Random random = new Random();  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < length; i++) {  
            int number = random.nextInt(base.length());  
            sb.append(base.charAt(number));  
        }  
        return sb.toString();  
    }  
      
      
    //拼接xml 请求路径  
    @SuppressWarnings("rawtypes")
	public static String getRequestXML(SortedMap<Object, Object> parame){  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("<xml>");  
        Set set = parame.entrySet();  
        Iterator iterator = set.iterator();  
        while(iterator.hasNext()){  
            Map.Entry entry = (Map.Entry) iterator.next();  
            String key = (String)entry.getKey();  
            String value = (String)entry.getValue();  
            //过滤相关字段sign  
            if("sign".equalsIgnoreCase(key)){  
                buffer.append("<"+key+">"+"<![CDATA["+value+"]]>"+"</"+key+">");  
            }else{  
                buffer.append("<"+key+">"+value+"</"+key+">");  
            }             
        }  
        buffer.append("</xml>");  
        return buffer.toString();  
    }  
      
      
    //返回微信服务  
     public static String setXml(String return_code,String return_msg){    
            return "<xml><return_code><![CDATA["+return_code+"]]></return_code><return_msg><![CDATA["+return_msg+"]]></return_msg></xml>";    
    }    
      
    //模拟微信回调接口  
     public static String callbakcXml(String orderNum){  
         return "<xml><appid><![CDATA[wx2421b1c4370ec43b]]></appid><attach><![CDATA[支付测试]]></attach><bank_type><![CDATA[CFT]]></bank_type><fee_type><![CDATA[CNY]]></fee_type> <is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[10000100]]></mch_id><nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str><openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid> <out_trade_no><![CDATA["+orderNum+"]]></out_trade_no>  <result_code><![CDATA[SUCCESS]]></result_code> <return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign><sub_mch_id><![CDATA[10000100]]></sub_mch_id> <time_end><![CDATA[20140903131540]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id></xml>";  
     }  
	
}